package com.yuanduan.mplus.view;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.webkit.HttpAuthHandler;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.cj.framework.app.BaseActivity;
import com.cj.framework.util.FileUtils;
import com.cj.framework.util.HttpImp;
import com.cj.framework.util.IHttp;
import com.cj.framework.util.RSAUtils;
import com.cj.framework.widget.CircleImageView;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.yuanduan.mplus.R;
import com.yuanduan.mplus.config.Config;
import com.yuanduan.mplus.model.DBManager;
import com.yuanduan.mplus.model.entity.CarInfoEntity;
import com.yuanduan.mplus.model.entity.PromotionEntity;
import com.yuanduan.mplus.model.entity.RS;
import com.yuanduan.mplus.model.entity.RSUserResults;
import com.yuanduan.mplus.model.entity.User;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * 旧版本首页
 */
public class MainActivity extends BaseActivity implements View.OnClickListener, NavigationView.OnNavigationItemSelectedListener {
    private long mExitTime;
    private IHttp iHttp;

    //最外层布局
    private DrawerLayout drawerLayout;

    //主界面头像
    private CircleImageView ci_content_userHeader;
    //上周情况的标题
    private TextView tv_situation1;
    private TextView tv_situation2;
    private TextView tv_situation3;
    private TextView tv_situation4;
    //上周情况的参数
    private TextView tv_grade1;
    private TextView tv_grade2;
    private TextView tv_grade3;
    private TextView tv_grade4;
    //推广
    private ImageView iv_promotion;
    //绑定车辆横条
    private LinearLayout ll_carbar;
    //开始行程
    private TextView tv_startTrip;
    //工具栏消息图标
    private ImageButton ib_message;
    //工具栏导航图标
    private ImageButton ib_person;
    //绑定车辆的内容区
    private TextView tv_car;
    //绑定车辆
    private TextView tv_changeCar;
    //上周情况的那个箭头
    private ImageView iv_userScore;
    //主界面头像下面文字
    private TextView tv_content_userInfo;

    //导航区个人信息
    private TextView tv_userInfo;
    private TextView tv_message;
    //导航区头像
    private CircleImageView ci_userHeader;
    //导航view
    private NavigationView navigationView;

    private Receiver receiver;
    private Receiver receiver1;

    //推广的url地址
    private User user;
    private String url;
    private int point;
    private String grade1;
    private String grade2;
    private String grade3;
    private String grade4;
    private String zxingId;

    private IHttp.HttpInfoCallbackWithIndex callback=new IHttp.HttpInfoCallbackWithIndex() {
        @Override
        public void onSucceed(Object result, int index) {
            if(TextUtils.isEmpty((CharSequence) result)){
                return;
            }
            switch (index){
                case 0:
                    //查询车辆牌照
                    CarInfoEntity carInfoEntity= (CarInfoEntity) Config.decry(result,CarInfoEntity.class);
                    if(carInfoEntity.getRS()==1){
                        tv_car.setText(carInfoEntity.getCarNumber());
                        user.setCarNumber(carInfoEntity.getCarNumber());
                        DBManager.getInstance(getApplicationContext()).updateUser(user);
                    }
                    break;
                case 1:
                    //积分状况
                    String result1=RSAUtils.decryptWithRSA((String) result);
                    try {
                        JSONObject points=new JSONObject(result1);
                        point=points.getInt("TotalIntegral");
                        tv_content_userInfo.setText(user.getRealName()+"\n积分"+point);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }

        @Override
        public void onFailed(Object result, int index) {

        }
    };

    @Override
    protected void findId() {
        ll_carbar= (LinearLayout) findViewById(R.id.carBar);
        ci_content_userHeader= (CircleImageView) findViewById(R.id.main_content_ci_userHeader);
        iv_promotion= (ImageView) findViewById(R.id.main_iv_prmotion);
        tv_grade1= (TextView) findViewById(R.id.main_content_grade1);
        tv_grade2= (TextView) findViewById(R.id.main_content_grade2);
        tv_grade3= (TextView) findViewById(R.id.main_content_grade3);
        tv_grade4= (TextView) findViewById(R.id.main_content_grade4);
        tv_situation1= (TextView) findViewById(R.id.main_content_tv_situation1);
        tv_situation2= (TextView) findViewById(R.id.main_content_tv_situation2);
        tv_situation3= (TextView) findViewById(R.id.main_content_tv_situation3);
        tv_situation4= (TextView) findViewById(R.id.main_content_tv_situation4);
        tv_content_userInfo= (TextView) findViewById(R.id.main_content_tv_userInfo);
        drawerLayout= (DrawerLayout) findViewById(R.id.main_drawerLayout);
        navigationView= (NavigationView) findViewById(R.id.main_navigationview);
        ib_person= (ImageButton) findViewById(R.id.main_content_ib_person);
        tv_startTrip= (TextView) findViewById(R.id.main_content_tv_startTrip);
        ib_message= (ImageButton) findViewById(R.id.main_content_ib_message);
        tv_car= (TextView) findViewById(R.id.main_content_tv_car);
        tv_changeCar= (TextView) findViewById(R.id.main_content_tv_changeCar);
        iv_userScore= (ImageView) findViewById(R.id.main_content_iv_userScore);
    }

    @Override
    protected void logic() {
        tv_startTrip.setOnClickListener(this);
        ib_message.setOnClickListener(this);
        tv_changeCar.setOnClickListener(this);
        iv_userScore.setOnClickListener(this);
        ib_person.setOnClickListener(this);
        iv_promotion.setOnClickListener(this);
        tv_content_userInfo.setOnClickListener(this);

        iHttp=new HttpImp();
        receiver=new Receiver();
        receiver1=new Receiver();
        IntentFilter filter=new IntentFilter("com.cj.updateMainDB");
        IntentFilter filter1=new IntentFilter("com.cj.updateMainImg");
        registerReceiver(receiver,filter);
        registerReceiver(receiver1,filter1);

        user=DBManager.getInstance(getApplicationContext()).getUser();

        //获取推广信息
        iHttp.httpInfoGet(Config.URL + Config.PROMOTION, new IHttp.HttpInfoCallback() {
            @Override
            public void onSucceed(Object result) {
                PromotionEntity entity= (PromotionEntity) Config.decry(result,PromotionEntity.class);
                if(entity==null){
                    return;
                }
                if(TextUtils.isEmpty(entity.getUrl())){
                    return;
                }
                url=Config.URL+entity.getUrl();
                iHttp.httpBitmapGet(Config.URL+entity.getMainImg(),iv_promotion);
            }
            @Override
            public void onFailed(Exception e) {

            }
        });




        RelativeLayout relativeLayout= (RelativeLayout) navigationView.getHeaderView(0);
        ImageView iv_arrow= (ImageView) relativeLayout.findViewById(R.id.main_nv_iv_arrow);
        tv_userInfo= (TextView) relativeLayout.findViewById(R.id.main_tv_message);
        ci_userHeader= (CircleImageView)relativeLayout.findViewById(R.id.main_circleImage);
        relativeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openActivity(SettingActivity.class);
            }
        });
        navigationView.setNavigationItemSelectedListener(this);

        if(Config.userType==-1){
            tv_content_userInfo.setText("游客");
            tv_userInfo.setText("游客");
            navigationView.inflateMenu(R.menu.menu_main_nv);
        }
        if(Config.userType==1){
            navigationView.inflateMenu(R.menu.menu_main_nv);
            tv_situation1.setText("驾驶里程");
            tv_situation2.setText("驾驶时长");
            tv_situation3.setText("安全驾驶评分");
            tv_situation4.setText("经济驾驶评分");
        }

        if(Config.userType==2){
            ll_carbar.setVisibility(View.GONE);
            navigationView.inflateMenu(R.menu.menu_main_nv_manager);
            tv_situation1.setText("驾驶总里程");
            tv_situation2.setText("驾驶总时长");
            tv_situation3.setText("安全驾驶员");
            tv_situation4.setText("经济驾驶员");
            tv_startTrip.setVisibility(View.GONE);
        }

        if(!TextUtils.isEmpty(user.getUserPhone())){
            if(Config.userType==1){
                tv_userInfo.setText(user.getRealName()+"\n"+user.getCarTeamName());
                tv_content_userInfo.setText(user.getRealName()+"\n积分"+0);
                HashMap<String,String> hashMap=new HashMap<>();
                hashMap.put("UserPhone",user.getUserPhone());
                hashMap.put("UserPassword",user.getUserPwd());
                hashMap.put("TargetUserPhone",user.getUserPhone());
                hashMap.put("Page","1");
                hashMap.put("Count","1");
                hashMap.put("Sorting","1");
                iHttp.httpInfoPostWithIndex(Config.URL+Config.USERINTEGRAL,Config.translateMap(hashMap),callback,1);
            }else if(Config.userType==2){
                tv_userInfo.setText(user.getRealName()+"\n"+user.getCarTeamName());
                tv_content_userInfo.setText(user.getRealName()+"\n"+"车队管理员");
            }
        }
        iHttp.httpBitmapGet(Config.URL + user.getUserHead(), new IHttp.HttpInfoCallback() {
            @Override
            public void onSucceed(Object result) {
                FileUtils.saveBitmap(Config.HEADLOCATION, (Bitmap) result);
                ci_userHeader.setBitmap((Bitmap) result);
                ci_content_userHeader.setBitmap((Bitmap) result);
            }

            @Override
            public void onFailed(Exception e) {

            }
        });

        //设置上周情况数据
        Calendar calendar=Calendar.getInstance();
        HashMap<String,String> hashMap=new HashMap<>();
        hashMap.put("UserPhone",user.getUserPhone());
        hashMap.put("UserPassword",user.getUserPwd());
        hashMap.put("TargetUserPhone",user.getUserPhone());
        if(calendar.get(Calendar.WEEK_OF_YEAR)==1){
            hashMap.put("YearCode",(calendar.get(Calendar.YEAR)-1)+"");
            hashMap.put("WeekCode",(52)+"");
        }else{
            hashMap.put("YearCode",calendar.get(Calendar.YEAR)+"");
            hashMap.put("WeekCode",(calendar.get(Calendar.WEEK_OF_YEAR)-1)+"");
        }
        //等待数据接入
        iHttp.httpInfoPost(Config.URL+Config.USERRESULTS, Config.translateMap(hashMap), new IHttp.HttpInfoCallback() {
            @Override
            public void onSucceed(Object result) {
                if(TextUtils.isEmpty((CharSequence) result)){
                    return;
                }
                //处理返回数据
                Log.e("xx",RSAUtils.decryptWithRSA((String) result));
                RSUserResults rsUserResults= (RSUserResults) Config.decry(result,RSUserResults.class);
                if(rsUserResults.getRS()==1){
                    tv_grade1.setText(rsUserResults.getMileage()+"km");
                    tv_grade2.setText(rsUserResults.getDrivingTime()+"h");
                    tv_grade3.setText(rsUserResults.getSecurity()+"");
                    tv_grade4.setText(rsUserResults.getEconomic()+"");
                }
//                grade1="";
//                grade2="";
//                grade3="";
//                grade4="";
//                tv_grade1.setText(grade1);
//                tv_grade2.setText(grade2);
//                tv_grade3.setText(grade3);
//                tv_grade4.setText(grade4);
            }

            @Override
            public void onFailed(Exception e) {
                Log.d("xx","shangzhou fail");
            }
        });

    }


    @Override
    protected int setLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.main_content_tv_startTrip:
                openActivity(DriverActivity.class);
                break;
            case R.id.main_content_ib_message:
                openActivity(MessageActivity.class);
                break;
            case R.id.main_content_tv_userInfo:
                if(Config.userType==2){
                    return;
                }
                openActivity(PointActivity.class);
                break;
            case R.id.main_content_tv_changeCar:
                IntentIntegrator intentIntegrator=new IntentIntegrator(this);
                intentIntegrator.setCaptureActivity(MplusCaptureActivity.class);
                intentIntegrator.initiateScan();
                break;
            case R.id.main_content_ib_person:
                drawerLayout.openDrawer(Gravity.LEFT);
                break;
            case R.id.main_content_iv_userScore:
                if(Config.userType==1){
                    openActivity(DriveScoreActivity.class);
                }else if(Config.userType==2){
//                    openActivity()
                }
                break;
            case R.id.main_iv_prmotion:
                if(!TextUtils.isEmpty(url)){
                    Bundle bundle=new Bundle();
                    bundle.putString("url",url);
                    openActivity(PromotionActivity.class,bundle);
                }else {
                    openActivity(PromotionActivity.class);
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result=IntentIntegrator.parseActivityResult(requestCode,resultCode,data);
        if(result!=null){
            if(result.getContents()!=null){
                zxingId=result.getContents();
                HashMap<String,String> hashMap=new HashMap<>();
                hashMap.put("UserPhone",user.getUserPhone());
                hashMap.put("UserPassword",user.getUserPwd());
                hashMap.put("TargetUserPhone",user.getUserPhone());
                hashMap.put("TargetCarID",zxingId);
                iHttp.httpInfoPost(Config.URL, Config.translateMap(hashMap), new IHttp.HttpInfoCallback() {
                    @Override
                    public void onSucceed(Object result) {
                        //处理数据
                        RS rs= (RS) Config.decry(result,RS.class);
                        if(rs.getRs()==1){
                            HashMap<String,String> hashMap1=new HashMap<String, String>();
                            hashMap1.put("CarID",zxingId);
                            iHttp.httpInfoPostWithIndex(Config.URL+Config.CARINFO,Config.translateMap(hashMap1),callback,0);
                        }else if(rs.getRs()==-2){
                            Toast.makeText(MainActivity.this,"绑定车辆失败",Toast.LENGTH_SHORT).show();
                        }

                        tv_car.setText(user.getCarNumber());
                    }

                    @Override
                    public void onFailed(Exception e) {

                    }
                });
            }
        }else{
            Toast.makeText(this,"扫码失败",Toast.LENGTH_SHORT).show();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            if(System.currentTimeMillis()-mExitTime>2000){
                mExitTime=System.currentTimeMillis();
                Toast.makeText(this,"再按一次退出程序",Toast.LENGTH_SHORT).show();
            }else{
                Intent intent=new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
            return true;
        }
        return super.onKeyDown(keyCode,event);
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.main_nv_consult:
                openActivity(Consult1Activity.class);
                break;
            case R.id.main_nv_tongzhi:
                openActivity(NotifyActivity.class);
                break;
            case R.id.main_nv_topic:
                openActivity(TopicActivity.class);
                break;
            case R.id.main_nv_store:
                openActivity(StoreActivity.class);
                break;
//            case R.id.main_nv_weeklygrade:
//                if(Config.userType==2){
////                    openActivity(DriveScoreActivity.class);
//                    openActivity(DriveAnalyseActivity.class);
//                }else{
//                    Bundle bundle=new Bundle();
//                    bundle.putString("realName",user.getRealName());
//                    bundle.putString("userPhone",user.getUserPhone());
//                    bundle.putString("userPwd",user.getUserPwd());
//                    openActivity(DriveScoreActivity.class,bundle);
////                    openActivity(DriveAnalyseActivity.class);
//                }
//                break;
//            case R.id.main_nv_record:
//                openActivity(DriveRecordActivity.class);
//                break;
            case R.id.main_nv_zxing:
                openActivity(ZxingActivity.class);
                break;
            case R.id.main_nv_comments:
                openActivity(CommentsReceivedActivity.class);
                break;
            case R.id.main_nv_setting:
                openActivity(Setting1Activity.class);
                break;
        }
        drawerLayout.closeDrawer(Gravity.LEFT);
        return true;
    }
    class Receiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            //更新信息，包括名字，图片；
            if(intent.getAction().equals("com.cj.updateMainDB")){
                user=DBManager.getInstance(getApplicationContext()).getUser();
                if(Config.userType==1){
                    tv_userInfo.setText(user.getRealName()+"\n"+user.getCarTeamName());
                    tv_content_userInfo.setText(user.getRealName()+"\n积分"+point);

                }else if(Config.userType==2){
                    tv_userInfo.setText(user.getRealName()+"\n车队管理员");
                    tv_content_userInfo.setText(user.getRealName()+"\n车队管理员");
                }
            }
            if(intent.getAction().equals("com.cj.updateMainImg")) {
                ci_content_userHeader.setBitmap(FileUtils.getBitmapFromFile(Config.HEADLOCATION));
                ci_userHeader.setBitmap(FileUtils.getBitmapFromFile(Config.HEADLOCATION));
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        unregisterReceiver(receiver1);
    }
}
